const Member = require("../model/member.model");
const User = require("../model/user.model");
// 使用模糊查询需要先引入Op
const seq = require("sequelize");
const Op = seq.Op;
class MemberService {
  /**
   * 创建
   * @returns {Promise<{code: string, message: string}>}
   * @param member
   */
  async createMember(member) {
    const res = await Member.create(member);
    return res.dataValues;
  }

  /**
   * 更新
   * @param id
   * @param member
   * @returns {Promise<boolean>}
   */
  async updateMember(id, member) {
    const res = await Member.update(member, { where: { id } });
    return res[0] > 0;
  }

  /**
   * 删除
   * @param id
   * @returns {Promise<boolean>}
   */

  async removeMember(id) {
    const res = await Member.destroy({ where: { id } });
    return res > 0;
  }

  /**
   * 恢复
   * @param id
   * @returns {Promise<boolean>}
   */

  async restoreMember(id) {
    const res = await Member.restore({ where: { id } });
    return res > 0;
  }

  async findMember({ pageNum, pageSize, goods_name, nick_name }) {
    const offset = (pageNum - 1) * pageSize;
    const whereOpt1 = {};

    nick_name &&
      Object.assign(whereOpt1, {
        nick_name: {
          [Op.like]: `%${nick_name}%`,
        },
      });
    const { count, rows } = await Member.findAndCountAll({
      offset: offset,
      limit: pageSize * 1,
      include: [
        {
          model: User,
          as: "user_info",
          attributes: ["nick_name"],
          where: whereOpt1,
        },
      ],
      order: [["createdAt", "DESC"]],
    });

    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }

  async checkIsApply(user_id) {
    const res =  await Member.findOne({
      where: {
        user_id,
        status: 0,
      },
    });

    return !!res;
  }

  async findMemberInfo(id) {
    const whereOpt = {};
    id && Object.assign(whereOpt, { id });

    const res = await Member.findOne({
      where: whereOpt,
      include: [
        {
          model: User,
          as: "user_info",
          attributes: ["nick_name"],
        },
      ],
    });

    return res ? res.dataValues : null;
  }
}

module.exports = new MemberService();
